/*
 * ResourceUtils.java
 *
 *  created: 26.8.2011
 *  charset: UTF-8
 *  license: MIT (X11) (See LICENSE file for full license)
 */
package cz.mp.util;

import cz.mp.util.app.ApplicationUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

/**
 *
 * @author Martin Pokorný
 * @version 0.1
 */
public class ResourceUtils {
    
    /** */
    private ResourceUtils() {        
    }

    /**
     * Získá {@link BufferedReader} ze souboru v {@code resources}.
     * Kódování je UTF-8.
     * 
     * @param resourcePath  (např. /resources/files/abc.txt)
     * @return 
     */
    static BufferedReader getBufferedReaderFromResource(
            String resourcePath) 
            throws IOException {
        if (resourcePath == null || resourcePath.isEmpty()) {
            throw new IllegalArgumentException("resourcePath is blank");
        }
        InputStream is = ResourceUtils.class.getResourceAsStream(resourcePath);
        if (is == null) {
            throw new IOException(resourcePath + " : resource not found!");
        }
        BufferedReader br = new BufferedReader(
                new InputStreamReader(is, "UTF-8"));
        return br;
    }
    
    
    /**
     * Získá obsah textového souboru v {@code resources}.
     * 
     * @param resourcePath  (např. /resources/files/abc.txt)
     * @return 
     */
    public static String readFileFromResource(String resourcePath) 
            throws IOException {
        BufferedReader br = getBufferedReaderFromResource(resourcePath);
        
        StringBuilder sb = new StringBuilder();
        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append(ApplicationUtils.EOL);
        }
        
        br.close();
        
        return sb.toString();
    }

    /**
     * Vrátí URL zdroje se souborem.
     *
     * @param resourcePath  (např. /resources/files/abc.txt)
     * @return URL zdroje s textem licence, nebo {@code null}, pokud se
     *      zadaný zdroj nenajde
     */
    public static URL getUrl(String resourcePath)  {
        URL result = null;
        if ((result = ResourceUtils.class.getResource(resourcePath)) != null) {
            return result;
        }
        return null;
    }

}   // ResourceUtils.java

